package com.binhthuan.catechist.client.form;

import gwtupload.client.IUploader;
import gwtupload.client.IUploadStatus.Status;
import gwtupload.client.IUploader.OnFinishUploaderHandler;
import gwtupload.client.IUploader.UploadedInfo;
import gwtupload.client.IUploader.Utils;

import com.binhthuan.catechist.client.ECApplication;
import com.binhthuan.catechist.client.component.ImageUploader;
import com.binhthuan.catechist.client.data.TrainerDS;
import com.binhthuan.catechist.client.data.callback.DSCallback;
import com.binhthuan.catechist.shared.constant.Parameter;
import com.binhthuan.catechist.shared.constant.Service;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.XMLParser;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.ValuesManager;
import com.smartgwt.client.widgets.form.fields.ButtonItem;
import com.smartgwt.client.widgets.form.fields.CanvasItem;
import com.smartgwt.client.widgets.form.fields.CheckboxItem;
import com.smartgwt.client.widgets.form.fields.DateItem;
import com.smartgwt.client.widgets.form.fields.HiddenItem;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.SpacerItem;
import com.smartgwt.client.widgets.form.fields.TextAreaItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.grid.events.DataArrivedEvent;
import com.smartgwt.client.widgets.tab.Tab;
import com.smartgwt.client.widgets.tab.TabSet;

public class TrainerInformationForm extends AbstractForm {

    private ValuesManager valuesManager;
    private ImageUploader uploader;

    public TrainerInformationForm() {
    }

    public TrainerInformationForm(TrainerDS dataSource) {
        super(dataSource);
        valuesManager = new ValuesManager();
        valuesManager.setDataSource(dataSource);
        setValuesManager(valuesManager);

        HiddenItem idField = new HiddenItem(Parameter.ID);

        TextItem patronSaintField = new TextItem(Parameter.PATRON_SAINT);
        patronSaintField.setTitle(ECApplication.getConstants().patronSaint());
        patronSaintField.setRequired(true);
        patronSaintField.setWidth("100%");

        TextItem lastNameField = new TextItem(Parameter.LAST_NAME);
        lastNameField.setTitle(ECApplication.getConstants().lastName());
        lastNameField.setRequired(true);
        lastNameField.setWidth("100%");

        TextItem firstNameField = new TextItem(Parameter.FIRST_NAME);
        firstNameField.setTitle(ECApplication.getConstants().firstName());
        firstNameField.setRequired(true);
        firstNameField.setWidth("100%");

        CheckboxItem genderField = new CheckboxItem(Parameter.MALE);
        genderField.setDefaultValue(true);
        genderField.setTitle(ECApplication.getConstants().isMale());

        uploader = new ImageUploader("images/layout/no-avatar.png", ECApplication.encodeURL(Service.UPLOAD), "128px", "128px");
        uploader.setI18Constants(ECApplication.getConstants());
        uploader.addOnFinishUploadHandler(new OnFinishUploaderHandler() {

            @Override
            public void onFinish(IUploader uploader) {
                if (uploader.getStatus() == Status.SUCCESS) {
                    UploadedInfo info = uploader.getServerInfo();
                    if (info != null) {
                        Document doc = XMLParser.parse(info.message);
                        String url = Utils.getXmlNodeValue(doc, "file-1-url");
                        setValue(Parameter.AVATAR, url);
                    }

                }
            }
        });
        CanvasItem imageAvatar = new CanvasItem();
        imageAvatar.setTitle(ECApplication.getConstants().avatar());
        imageAvatar.setCanvas(uploader.createCanvas(true));
        imageAvatar.setRowSpan(5);

        HiddenItem avatarField = new HiddenItem(Parameter.AVATAR);
        avatarField.setTitle(ECApplication.getConstants().avatar());

        DateItem birthdayField = new DateItem(Parameter.BIRTHDAY);
        birthdayField.setTitle(ECApplication.getConstants().birthday());
        birthdayField.setWidth("100%");

        DateItem feastDateField = new DateItem(Parameter.FEAST_DAY);
        feastDateField.setTitle(ECApplication.getConstants().feastDay());
        feastDateField.setWidth("100%");

        TextItem addressField = new TextItem(Parameter.ADDRESS);
        addressField.setTitle(ECApplication.getConstants().address());
        addressField.setWidth("100%");

        TextItem phoneField = new TextItem(Parameter.PHONE);
        phoneField.setTitle(ECApplication.getConstants().phone());
        phoneField.setWidth("100%");

        SelectItem areaField = new SelectItem(Parameter.AREA);
        areaField.setTitle(ECApplication.getConstants().area());
        areaField.setWidth("100%");

        TextItem emailField = new TextItem(Parameter.EMAIL);
        emailField.setTitle(ECApplication.getConstants().email());
        emailField.setWidth("100%");

        DateItem joinDateField = new DateItem(Parameter.JOIN_DATE);
        joinDateField.setTitle(ECApplication.getConstants().joinDate());
        joinDateField.setWidth("100%");

        SelectItem statusField = new SelectItem(Parameter.STATUS);
        statusField.setTitle(ECApplication.getConstants().status());
        statusField.setWidth("100%");

        CheckboxItem activeField = new CheckboxItem(Parameter.ACTIVE);
        activeField.setTitle(ECApplication.getConstants().active());
        activeField.setDefaultValue(false);

        TextAreaItem commentField = new TextAreaItem(Parameter.COMMENT);
        commentField.setTitle(ECApplication.getConstants().comment());
        commentField.setWidth("100%");

        TabSet tabSet = new TabSet();
        tabSet.setWidth(600);
        tabSet.setHeight(300);

        Tab personalTab = new Tab(ECApplication.getConstants().personalInformation());
        Tab advanceTab = new Tab(ECApplication.getConstants().advanceInformation());
        Tab accountTab = new Tab(ECApplication.getConstants().account());

        DynamicForm personalForm = new DynamicForm();
        personalForm.setNumCols(4);
        personalForm.setColWidths("15%", "30%", "15%", "30%");
        personalForm.setFields(idField, avatarField, patronSaintField, imageAvatar, lastNameField, firstNameField,
                genderField, birthdayField, phoneField, addressField, emailField, areaField);
        personalForm.setDataSource(valuesManager.getDataSource());
        personalForm.setValuesManager(getValuesManager());
        personalTab.setPane(personalForm);

        DynamicForm advanceForm = new DynamicForm();
        advanceForm.setNumCols(4);
        advanceForm.setFields(joinDateField, new SpacerItem(), feastDateField, new SpacerItem(), statusField,
                new SpacerItem(), activeField, new SpacerItem(), commentField, new SpacerItem());
        advanceForm.setDataSource(valuesManager.getDataSource());
        advanceForm.setValuesManager(getValuesManager());
        advanceTab.setPane(advanceForm);

        DynamicForm accountForm = new DynamicForm();
        accountForm.setNumCols(4);
        accountForm.setFields();
        accountForm.setValuesManager(getValuesManager());
        accountTab.setPane(accountForm);

        tabSet.setTabs(personalTab, advanceTab, accountTab);
        CanvasItem c = new CanvasItem();
        c.setShowTitle(false);
        c.setCanvas(tabSet);
        ButtonItem saveButton = createSaveButton();
        setFields(c, saveButton);
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.smartgwt.client.widgets.form.DynamicForm#editRecord(com.smartgwt.
     * client.data.Record)
     */
    @Override
    public void editRecord(Record record) {
        valuesManager.editRecord(record);
        uploader.setImage(record.getAttribute(Parameter.AVATAR));
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.smartgwt.client.widgets.form.DynamicForm#editNewRecord()
     */
    @Override
    public void editNewRecord() {
        valuesManager.editNewRecord();
        uploader.reset();
    }

    /* (non-Javadoc)
     * @see com.binhthuan.catechist.client.form.AbstractForm#setValue(java.lang.String, java.lang.String)
     */
    @Override
    public void setValue(String fieldName, String value) {
        valuesManager.getItem(fieldName).setValue(value);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.binhthuan.catechist.client.form.AbstractForm#saveClick()
     */
    @Override
    public void saveClick() {
        valuesManager.saveData(new DSCallback() {

            @Override
            public void onSuccess() {
                onUpdateSuccess();
            }

            @Override
            public void onFailure(DSResponse response, Object rawData) {
                onUpdateFailure(response, rawData);
            }
        });
        fireEvent(new DataArrivedEvent(null));
    }
}
